import requests
from urllib import parse
import json
import time
import re
import sys

username = '136xxxx'
password = 'xxxxxxx'
steps = '11018'

headers = {
    "User-Agent": "MiFit/4.6.0 (iPhone; iOS 14.0.1; Scale/2.00)",
    "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
}


def loginByPassword():
    url = "https://api-user.huami.com/registrations/+86" + username + "/tokens"
    redirect_uri = "https://s3-us-west-2.amazonaws.com/hm-registration/successsignin.html"
    data = {
        "client_id": "HuaMi",
        "password": password,
        "redirect_uri": redirect_uri,
        "token": "access",
    }
    try:
        resp = requests.post(url, headers=headers, data=data)
        result = parse.urlparse(resp.url)
        getAccess = parse.parse_qs(result.query)
        if 'access' in getAccess:
            access = getAccess['access'][0]
            return access
        raise NameError
    except NameError:
        print("登录失败， 请检查账号密码")
        sys.exit()


def getAccessToken(code):
    url = "https://account.huami.com/v2/client/login"
    data = {
        "app_name": "com.xiaomi.hm.health",
        "app_version": "4.6.0",
        "code": code,
        "country_code": "CN",
        "device_id": "2C8B4939-0CCD-4E94-8CBA-CB8EA6E613A1",
        "device_model": "phone",
        "grant_type": "access_token",
        "third_name": "huami_phone",
    }
    try:
        resp = requests.post(url, headers=headers, data=data)
        token_info = json.loads(resp.text)["token_info"]
        return token_info
    except:
        print("获取AccessToken失败")
        sys.exit()


def pushBandData(steps, user_id, app_token):
    data = {
        "userid": user_id,
        "last_sync_data_time": 1597306381,
        "device_type": 0,
        "last_deviceid": "DA932FFFFE8816E7",
        "data_json": buildDataJson(steps),
    }
    try:
        url = 'https://api-mifit-cn.huami.com/v1/data/band_data.json?&t=' + \
            str(int(time.time()))
        headers["apptoken"] = app_token
        requests.post(url, headers=headers, data=data)
        print('上传步数成功 step:' + steps);
    except:
        print("上传步数失败")
        sys.exit()


def buildDataJson(steps):
    getTime = time.strftime("%Y-%m-%d", time.localtime())
    with open('./data.json', 'r', encoding='utf-8') as f:
        data_json = f.read()

    data_json = data_json.replace(
        re.match(r'.*?date":"(.*?)","data.*?', data_json)[1], getTime)
    data_json = data_json.replace(
        re.match(r'.*?ttl\\":(.*?),\\"dis.*?', data_json)[1], steps)
    return data_json


def main():
    code = loginByPassword()
    token = getAccessToken(code)
    app_token = token["app_token"]
    user_id = token["user_id"]
    pushBandData(steps, user_id, app_token)


if __name__ == '__main__':
    main()
